// <copyright file="FileSize.cs" company="Sinclair Community College">
// Copyright (c) Sinclair Community College. All rights reserved.
// </copyright>

namespace SinclairCC.AppVSuite.DuplicateRootDetector
{
    using System;

    /// <summary>
    /// This class contains a function to convert a file's size in bytes to
    /// a user-friendly string that indicates the size in kilobytes (KB),
    /// megabytes (MB), etc., whichever is appropriate.
    /// </summary>
    public class FileSize
    {
        /// <summary>
        /// Converts a file size in bytes to a string containing the size
        /// in kilobytes (KB), megabytes (MB), etc., whichever is appropriate.
        /// </summary>
        /// <param name="number">
        /// The file size, in bytes, to be converted.
        /// </param>
        /// <returns>
        /// Returns a string containing a user-friendly representation of the file's size.
        /// </returns>
        public static string AutoFormat(long number)
        {
            float convertedNumber;

            System.Collections.Generic.SortedList<byte, string> abbrevList = new System.Collections.Generic.SortedList<byte, string>(4);

            abbrevList.Add(1, "KB"); // kilobyte
            abbrevList.Add(2, "MB"); // megabyte
            abbrevList.Add(3, "GB"); // gigabyte
            abbrevList.Add(4, "TB"); // terabyte

            /*
             * These are included for when file sizes commonly start getting
             * into petabyte range and beyond.
            abbrevList.Add(5, "PB");
            abbrevList.Add(6, "EB");
            abbrevList.Add(7, "ZB");
            abbrevList.Add(8, "YB");
            */

            for (int i = abbrevList.Count - 1; i >= 0; i--)
            {
                long powerOfTwo = (long)Math.Pow(2, abbrevList.Keys[i] * 10);
                if (number >= powerOfTwo)
                {
                    convertedNumber = (float)number / powerOfTwo;
                    return string.Format("{0} {1}", convertedNumber.ToString("N2", System.Globalization.CultureInfo.CurrentUICulture), abbrevList.Values[i]);
                }
            }

            return string.Format("{0} bytes", number.ToString("N0", System.Globalization.CultureInfo.CurrentUICulture));
        }
    }
}
